<?php

namespace app\common\letterbusiness;

use \think\Request;
use \think\Session;
use think\Config as Configbn;
use app\common\mysql\LetterUsers as usersMysql;
use app\common\mysql\UserFriends as userFriendsMysql;
use app\common\letterbusiness\Scheme as schemeBn;
use app\common\letterbusiness\Match as matchBn;
use app\common\redis\db0\Userinfo as userRedis;
use app\extra\SmsSDK\Jvhe as MessageBn;
use app\common\letterbusiness\upload\Upload as uploadBn;
use app\common\letterbusiness\user\Point as pointBn;
use app\common\letterbusiness\Quicklogin as quickloginBn;
use app\common\letterbusiness\Coupon as couponBn;
use app\common\letterbusiness\UserMessage as userMessageBn;
use app\common\behavior\push\PushBatch as pushBn;
use app\common\letterbusiness\user\Hd as hdBn;

class User extends \app\common\letterbusiness\AbstractModel {

    public static function code_type() {
        return array(
            1 => '注册',
            2 => '绑定手机号',
            3 => '忘记密码',
            4 => '邀请好友'
        );
    }

    /**
     * 管理专家
     */
    public static function myUserMange($user_id) {
        $data = array(
            '23' => array(29, 30, 31, 108, 110, 23), //张雨馨
            '135' => array(26, 27, 28, 111, 112, 135), //高峰
            '123' => array(57, 58, 59, 89, 90, 123), //王小红
            '148' => array(1, 2, 106, 150, 151, 148), //蓝小攀
            '134' => array(3, 10, 17, 116, 149, 134), //庄嘉莹
            '142' => array(18, 19, 54, 114, 115, 142), // 赵敏
            '155' => array(39, 40, 42, 99, 100, 155), // 郑铭捷
            '124' => array(60, 62, 63, 87, 88, 124), // 安伟华
            '146' => array(36, 37, 38, 101, 104, 146), // 叶孟阳子
            '121' => array(43, 44, 45, 94, 97, 121), // 沈明义
            '128' => array(64, 66, 68, 94, 97, 128), // 周良城
//            '142' => array(18, 19,54,114,115), // 赵敏
        );
        return isset($data[$user_id]) ? $data[$user_id] : array();
    }

    /*
     * 内部员工
     *
     * */

    public static function expertinfo($user_id, $post = array()) {
        $expertids = self::myUserMange($user_id);
        $experinfo = array();
        foreach ($expertids as $key => $val) {
            $experinfoarray = self::userInfo($val, 'user_id,nickname,localheadimgurl as headimgurl,cat_id', $post);
            if (empty($experinfoarray)) {
                continue;
            }
            $experinfo[$key]['user_id'] = $experinfoarray['user_id'];
            $experinfo[$key]['nickname'] = $experinfoarray['nickname'];
            $experinfo[$key]['headimgurl'] = $experinfoarray['headimgurl'];
            $experinfo[$key]['cat_id'] = $experinfoarray['cat_id'];
        }
        return $experinfo;
    }

    /*
     * 公司内部人员重定向
     *
     * */

    public static function userMange($user_id, $expert_id) {
        if ($expert_id && !empty($expert_id)) {
            $expert_array = self::myUserMange($user_id);
            if (in_array($expert_id, $expert_array)) {
                $user_id = $expert_id;
            }
        }
        return $user_id;
    }

    /**
     * 会员列表
     * page
     * count
     * need_total
     */
    public static function userlist($params) {
        self::_checkPageAndCount($params);
        $where = self::_getWhere($params);
        $listdata = usersMysql::name('letter_users')
                ->where($where)
                ->limit($params['offset'], $params['count'])
                ->select();
        if (!empty($listdata)) {
            $listdata = self::_adapterList($listdata);
        }
        if (isset($params["need_total"]) && $params["need_total"] == 1) {
            return array("listdata" => $listdata, "total" => self::total($params));
        }
        return array("listdata" => (array) $listdata);
    }

    /**
     * 获取Query条件
     *
     * @param array $params
     * @return array
     */
    protected static function _getQuery($params) {
        $query = array();
        if (isset($params["cat_id"])) { //即时
            $query['cat_id'] = $params["cat_id"];
        }
        if (isset($params["status"])) { //即时
            $query['status'] = $params["status"];
        }

        if (isset($params["user_type"])) { //即时
            if (isset($params["user_type"])) { //即时
                $query['user_type'] = $params["user_type"];
            }
        }
        if (isset($params["recommend"])) { //即时
            $query['recommend'] = $params["recommend"];
        }
        if (isset($params["nickname"])) { //昵称
            $query['nickname'] = $params["nickname"];
        }
        if (isset($params["user_type"])) { //用户类型
            $query['user_type'] = $params["user_type"];
        }
        if (isset($params["user_type2"])) { //用户类型
            $query['user_type2'] = $params["user_type2"];
        }
        if (isset($params["rank"])) { //用户级别
            $query['rank'] = $params["rank"];
        }
        if (isset($params["mobile"])) { //用户手机号
            $query['mobile'] = $params["mobile"];
        }
        if (isset($params["user_id"])) { //用户id
            $query['user_id'] = $params["user_id"];
        }
        if (isset($params['code_type'])) {
            $query['code_type'] = $params['code_type'];
        }

        if (isset($params["str_time"])) { //时间
            $query['str_time'] = $params["str_time"];
        }
        if (isset($params["end_time"])) { //时间
            $query['end_time'] = $params["end_time"];
        }
        return $query;
    }

    /**
     * 后台会员列表
     * page
     * count
     * need_total
     */
    public static function adminuserlist($params) {
        self::_checkPageAndCount($params);
        $where = self::_getWhere($params);
        $order = self::_getOrder($params);
        if (isset($params['user_id']) && !empty($params['user_id'])) {
            $where['user_id'] = $params['user_id'];
        }
        $query = self::_getQuery($params);
        $pageParam['query'] = $query;
        $listdata = usersMysql::name('letter_users')
                ->alias('u')
                ->field('u.*,ud.*,u.add_time as reg_time,ud.add_time as add_time ')
                ->join('__USER_DEVICE__ ud', 'u.uuid = ud.uuid', 'left')
                ->where($where)
                ->order($order)
                ->paginate($params['count'], false, $pageParam);

        if (!empty($listdata)) {
            $listdata = self::_adapterList($listdata);
        }

        return $listdata;
    }

    /**
     * 用户信息
     */
    public static function apiUserInfo($user_id) {
        $data = usersMysql::name('letter_users')
                ->where(array("user_id" => $user_id))
                ->find();
        return $data;
    }

    /**
     * 适配输出
     *
     * @params
     * @return array
     */
    protected static function _adapterList($result) {

        foreach ($result as $k => $val) {
            $total = usersMysql::name('orders')->where(array('user_id' => $val['user_id']))->count();
            $result[$k]['buy_scheme_count'] = $total ? $total : 0;
            $result[$k]['nickname'] = $val['nickname'] ? $val['nickname'] : '球宝' . $val['user_id'];
        }
        return $result;
    }

    /**
     * 获取_getOrder条件
     *
     * @param array $params
     * @return array
     */
    protected static function _getOrder($params) {
        $order = array();
        if (isset($params['_order']) && !empty($params['_order'])) {
            $order[$params['_order']] = $params['_sort'];
        } else {
            $order = 'user_id desc';
        }
        return $order;
    }

    /**
     * 获取where条件
     *
     * @param array $params
     * @return array
     */
    protected static function _getWhere($params) {
        $where = array();
        if (isset($params["cat_id"]) && !empty($params['cat_id'])) { //即时
            $where['cat_id'] = $params["cat_id"];
        }
        if (isset($params["status"]) && $params['status'] >= 0) { //即时
            $where['status'] = $params["status"];
        }
        if (isset($params["mobile"]) && !empty($params['mobile'])) { //手机号
            $where['mobile'] = $params["mobile"];
        }
        if (isset($params['code_type']) && !empty($params['code_type'])) {
            $where['code_type'] = $params['code_type'];
        }
        if (isset($params["user_type"]) && !empty($params["user_type"])) { //即时
            $where['user_type'] = $params["user_type"];
        }
        if (isset($params["recommend"]) && !empty($params["recommend"])) { //推荐
            $where['recommend'] = $params["recommend"];
        }
        if (isset($params["nickname"]) && !empty($params['nickname'])) { //昵称
            $where['nickname'] = ['like', '%' . $params["nickname"] . '%'];
        }
        if (isset($params["user_type2"]) && !empty($params['user_type2'])) { //用户类型
            $where['user_type2'] = $params["user_type2"];
        }
//        if (isset($params["user_id"]) && $params['user_id'] >= 0) { //用户类型
//            $where['user_id'] = $params["user_id"];
//        }
        if (isset($params["user_type2"]) && !empty($params['user_type2'])) { //用户类型
            $where['user_type2'] = $params["user_type2"];
        }
        if (isset($params["recommend"]) && !empty($params['recommend'])) { //用户类型
            $where['recommend'] = $params["recommend"];
        }
        if (isset($params["rank"]) && !empty($params['rank'])) { //用户类型
            $Lv = pointBn::userLv();
            $userLv = $Lv[$params["rank"]];
            $where['lv'] = array('between', [$userLv['min'], $userLv['max']]);
        }

        if (isset($params["str_time"]) && !empty($params['end_time'])) { //用户类型
            if (isset($params['str_time'])) {
                $params['str_time'] = strtotime($params['str_time']);
            }
            if (isset($params['end_time'])) {
                $params['end_time'] = strtotime($params['end_time']);
            }
            $where['add_time'] = array('between', [$params['str_time'], $params['end_time']]);
        }
        return $where;
    }

    /**
     * 计算总数
     *
     * @param array $params
     * @return int
     */
    public static function total($params) {
        $where = self::_getWhere($params);
        $count = usersMysql::name('letter_users')
                ->where($where)
                ->count();
        return $count;
    }

    /**
     * 关注
     * @post
     * user_id
     */
    public static function followList($params) {
        self::_checkPageAndCount($params);
        $where = array('f.user_id' => $params['user_id']);
        $listdata = userFriendsMysql::name('user_friends')
                ->field("f.user_id,f.user_byid,f.add_time,u.nickname,u.headimgurl,u.wins,u.lose,u.user_sign,1 as is_follow,u.lv,u.localheadimgurl,u.winrate")
                ->alias('f')
                ->join('__USERS__ u', 'u.user_id = f.user_byid', 'left')
                ->where($where)
                ->limit($params['offset'], $params['count'])
                ->select();
        if (!empty($listdata)) {
            $listdata = self::_adapterfollowList($listdata);
        }
        if (isset($params["need_total"]) && $params["need_total"] == 1) {
            return array("listdata" => $listdata, "total" => self::followTotal($params));
        }
        return array("listdata" => (array) $listdata);
    }

    /**
     * 粉丝
     * @post
     * user_id
     */
    public static function myfansList($params) {
        self::_checkPageAndCount($params);
        $where = array('f.user_byid' => $params['user_byid']);
        $listdata = userFriendsMysql::name('user_friends')
                ->field("f.user_id,f.user_id,f.add_time,u.nickname,u.headimgurl,u.wins,u.lose,u.user_sign,u.lv,u.localheadimgurl")
                ->alias('f')
                ->join('__USERS__ u', 'u.user_id = f.user_id', 'left')
                ->where($where)
                ->limit($params['offset'], $params['count'])
                ->select();
        if (!empty($listdata)) {
            $listdata = self::_adapterfollowList($listdata);
        }
        if (isset($params["need_total"]) && $params["need_total"] == 1) {
            return array("listdata" => $listdata, "total" => self::followTotal($params));
        }
        return array("listdata" => (array) $listdata);
    }

    /**
     * 粉丝
     * @post
     * user_id
     */
    public static function myfriendsList($params) {
        self::_checkPageAndCount($params);
        $where = array();
        if (isset($params["user_id"]) && !empty($params['user_id'])) { //即时
            $where['f.user_id'] = $params["user_id"];
        }
        if (isset($params['user_byid']) && !empty($params['user_byid'])) { //手机号
            $where['user_byid'] = $params["user_byid"];
        }
        $query = self::_getQuery($params);
        $pageParam['query'] = $query;
        $listdata = userFriendsMysql::name('user_friends')
                ->field("f.rid,f.user_id,f.user_byid,f.add_time,u.nickname,u.headimgurl,u.wins,u.lose,u.user_sign,u.lv,u.localheadimgurl,b.nickname as bnickname,b.headimgurl as bheadimgurl,b.wins as bwins,b.lose as blose,b.user_sign as buser_sign,b.lv as blv,b.localheadimgurl as blocalheadimgurl")
                ->alias('f')
                ->where($where)
                ->join('__USERS__ u', 'u.user_id = f.user_id', 'left')
                ->join('__USERS__ b', 'b.user_id = f.user_byid', 'left')
                ->limit($params['offset'], $params['count'])
                ->paginate($params['count'], false, $pageParam);

        if (!empty($listdata)) {
            
        }
        return $listdata;
    }

    /**
     * 适配输出
     *
     * @params
     * @return array
     */
    protected static function _adapterfollowList($result) {
        foreach ($result as $k => $v) {
            $result[$k]['grade'] = pointBn::getLevel($v['lv']);
        }
        return $result;
    }

    /**
     * 计算总数
     *
     * @param array $params
     * @return int
     */
    public static function followTotal($params) {
        if (isset($params['user_id']) && !empty($params['user_id'])) {
            $where['user_id'] = $params['user_id'];
        }
        if (isset($params['user_byid']) && !empty($params['user_byid'])) {
            $where['user_byid'] = $params['user_byid'];
        }
        $count = userFriendsMysql::name('user_friends')
                ->where($where)
                ->count();
        return $count;
    }

    /**
     * 专家列表足球篮球
     * @param array $params
     * cat_id
     * user_id 当前用户
     * page
     * count
     *
     */
    public static function expertList($params) {
        self::_checkPageAndCount($params);
        $where = self::_getWhere($params);
        if (isset($params['recommend'])) {
            $orderby = "recommend desc";
        } else {
            $orderby = "user_id desc";
        }
        $listdata = usersMysql::name('letter_users')
                ->field("user_id,nickname,headimgurl,localheadimgurl,wins,lose,winrate,user_sign,lv")
                ->where($where)
                ->order($orderby)
                ->limit($params['offset'], $params['count'])
                ->select();
        if (!empty($listdata)) {
            $listdata = self::_adapterexpertList($listdata, $params);
        }
        if (isset($params["need_total"]) && $params["need_total"] == 1) {
            return array("listdata" => $listdata, "total" => self::expertTotal($params));
        }
        return array("listdata" => (array) $listdata);
    }

    /**
     * 计算总数
     *
     * @param array $params
     * @return int
     */
    public static function expertTotal($params) {
        $where = self::_getWhere($params);
        $count = usersMysql::name('letter_users')
                ->where($where)
                ->count();
        return $count;
    }

    /**
     * 适配输出
     *
     * @params
     * @return array
     */
    protected static function _adapterexpertList($result, $params) {
        foreach ($result as $k => $v) {
            $result[$k]['is_follow'] = 0;
            $result[$k]['grade'] = pointBn::getLevel($v['lv']);
            //是否关注
            if (isset($params['user_id']) && $params['user_id'] > 0) {
                $result[$k]['is_follow'] = self::isFollow($params['user_id'], $v['user_id']);
            }
        }

        return $result;
    }

    /**
     * 用户是否关注
     * user_id 当前用户
     * user_byid 被关注用户
     */
    public static function isFollow($user_id, $user_byid) {
        $where = array('user_id' => $user_id, 'user_byid' => $user_byid);
        $count = userFriendsMysql::name('user_friends')
                ->where($where)
                ->count();
        return $count;
    }

    /**
     * 关注记录
     * user_id 当前用户
     * user_byid 被关注用户
     */
    public static function addFollow($user_id, $user_byid) {
        $where = array('user_id' => $user_id, 'user_byid' => $user_byid);
        if ($user_id == $user_byid) {
            exception('不能关注自己', 10000003);
        }
        //用户ID是否存在
        $usercount = usersMysql::name('letter_users')
                ->where(array("user_id" => $user_byid))
                ->count();
        if ($usercount == 0) {
            exception('关注用户不存在', 10000003);
        }
        $count = userFriendsMysql::name('user_friends')
                ->where($where)
                ->count();
        if ($count > 0) {
            $r = userFriendsMysql::name('user_friends')->where($where)
                    ->delete();
            if ($r == true) {
                exception('取消关注', 200);
            }
            exception('取消关注失败', 10000003);
        }
        $data['user_id'] = $user_id;
        $data['user_byid'] = $user_byid;
        $data['add_time'] = time();
        $r = userFriendsMysql::name('user_friends')->insertGetId($data);
        if ($r) {
            exception('关注成功', 200);
        }
        exception('关注失败', 10000003);
        return $count;
    }

    /**
     * 专家详情
     * user_id
     * current_user_id  当前用户
     */
    public static function experInfo($post) {
        //专家信息
        $data['user'] = self::UserInfo($post['user_id'], 'user_id,nickname,headimgurl,user_type,wins,lose,user_sign,lv,(friends_count+friends_base) as friendscount,lose20,win20,lose50,win50,winrate');
        //是否关注
        unset($data['user']['sso']);
        $data['user']['is_follow'] = 0;
        if (isset($post['current_user_id']) && $post['current_user_id'] > 0) {
            $data['user']['is_follow'] = self::isFollow($post['current_user_id'], $post['user_id']);
        }
        //最近赢几次，最近连红几场
        $data['latelyredn'] = schemeBn::latelyRedN(array('user_id' => $post['user_id']));
        $data['user']['latelyred'] = schemeBn::latelyRed(array('user_id' => $post['user_id']));
        $data['tenlyredn'] = schemeBn::latelyRedN(array('user_id' => $post['user_id'], 'total' => 10));
        $data['twentylyredn'] = array('wincount' => $data['user']['win20'], 'losecount' => $data['user']['lose20']); //schemeBn::latelyRedN(array('user_id' => $post['user_id'], 'total' => 20));
        $data['fiftylyredn'] = array('wincount' => $data['user']['win50'], 'losecount' => $data['user']['lose50']); //schemeBn::latelyRedN(array('user_id' => $post['user_id'], 'total' => 50));
        //最高连赢数
        $data['user']['hightred'] = schemeBn::latelyHightRed(array('user_id' => $post['user_id']));
        //粉丝数
        // $data['user']['friendscount'] = self::followTotal(array('user_byid' => $post['user_id']));
        return $data;
    }

    /**
     * 计算用户登录的sso信息
     */
    public static function calcSso($memberId) {
        $key = Config('auth_key');

        $sso = rawurlencode(authcode($memberId, "ENCODE", $key));

        return $sso;
    }

    /**
     * 解密用户登录的sso信息
     */
    public static function decodeSso($sso) {
        $key = Config('auth_key');
        $result = authcode(rawurldecode($sso), "DECODE", $key);

        return $result;
    }

    /*
     *
     * 注册第三方注册
     *
     */

    public static function adduser($data) {
        $datap['reg_time'] = time();
        $datap['last_login'] = time();
        $datap['nickname'] = $data['nickname'];
        $datap['headimgurl'] =$datap['avatar']  = isset($data['localheadimgurl']) && !empty($data['localheadimgurl']) ? $data['localheadimgurl'] : $data['headimgurl'];
        $datap['localheadimgurl'] = isset($data['localheadimgurl']) && !empty($data['localheadimgurl']) ? $data['localheadimgurl'] : $data['headimgurl'];
        $datap['province'] = $data['province'];
        $datap['unionid'] = $data['unionid'];
        $datap['openid'] = $data['openid'];
        usersMysql::startTrans();
        $userd = usersMysql::name('letter_users')->insertGetId($datap);
        if ($userd) {
            $user = self::userInfo($userd);
            $user['sso'] = User::calcSso($user['user_id']);
            $user['is_register'] = 1;

            usersMysql::commit();
            return $user;
        } else {
            usersMysql::rollback();
            exception('注册失败！', 10000003);
        }
    }

    /**
     * 用户信息
     */
    public static function getUserInfo($where = array(), $field = '') {
        $info = usersMysql::name('LetterUsers')
                ->field($field)
                ->where($where)
                ->find();
        return $info;
    }

    /**
     * 用户信息
     */
    public static function userInfo($user_id, $field = '', $where = array()) {
        if ($field) {
            $info = usersMysql::name('letter_users')
                    ->field($field)
                    ->where(array('user_id' => $user_id))
                    ->where($where)
                    ->find();
        } else {
            $info = usersMysql::name('letter_users')
                    ->field('user_id,nickname,headimgurl,unionid,openid,localheadimgurl,sex,status,level as lv,mobile,readnum')
                    ->where(array('user_id' => $user_id))
                    ->find();
        }
        if ($info) {
            $info['sso'] = self::calcSso($user_id);
        }

        return $info;
    }

    /**
     * 分析sso信息
     *
     * @param string $sso
     */
    public static function analyzeSso($sso) {
        $memberId = self::decodeSso($sso);
        if (!$memberId) {
            exception('用户不存在', 100103);
        }
        $member = self::userInfo($memberId);
        if (!$member) {
            exception('用户不存在', 100103);
        }
        return $member;
    }

    /*
     *
     * 编辑
     *
     */

    public static function updateheadimgurl($post) {
        $userimg = isset($post['headimgurl']) ? $post['headimgurl'] : "";
        if ($userimg) {

            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $userimg)) {

                $data['headimgurl'] = uploadBn::uploadav($userimg)['dest_file_name'];

                $r = usersMysql::name('letter_users')->where(array('user_id' => $post['user_id']))->update($data);

                $userinfo = self::userInfo($post['user_id']);
                $userinfo['sso'] = User::calcSso($userinfo['user_id']);
                return $userinfo;
            }
        }
        exception("修改头像失败！", 110030);
    }

    /*
     *
     * 编辑
     *
     */

    public static function updateinfo($post) {
        if (isset($post['nickname'])) {
            $user_id = usersMysql::name('letter_users')->where(array('nickname' => $post['nickname']))->value('user_id');
            if ($user_id > 0) {
                if ($user_id != $post['user_id']) {
                    exception("此昵称已被使用过了！", 110030);
                }
            }
        }
        $data['user_updatetime'] = time();
        $data['sex'] = isset($post['sex']) ? $post['sex'] : 1;
        $data['nickname'] = $post['nickname'];
        $r = usersMysql::name('letter_users')->where(array('user_id' => $post['user_id']))->update($data);
        if ($r) {
            $userinfo = self::userInfo($post['user_id']);
            $userinfo['sso'] = User::calcSso($userinfo['user_id']);
            return $userinfo;
        } else {
            exception('修改失败', 110030);
        }
    }

    /*
     *
     * 编辑
     *
     */

    public static function edit($post) {
        if (isset($post['nickname'])) {
            $user_id = usersMysql::name('letter_users')->where(array('nickname' => $post['nickname']))->value('user_id');
            if ($user_id > 0) {
                if ($user_id != $post['user_id']) {
                    exception("此昵称已被使用过了！", 110030);
                }
            }
        }
        $data = $post;
        $data['user_updatetime'] = time();
        $data['sex'] = isset($post['sex']) ? $post['sex'] : 1;
        $data['nickname'] = $post['nickname'];
        $data['localheadimgurl'] = $data['headimgurl'];

        $r = usersMysql::name('letter_users')->where(array('user_id' => $post['user_id']))->update($data);
        return $r;
    }

    /*
     *
     * 注册
     *
     */

    public static function add($data) {
        $datap = $data;
        $datap['add_time'] = time();
        $datap['user_lasttime'] = time();
        $datap['nickname'] = $data['nickname'];
        $datap['headimgurl'] = isset($data['localheadimgurl']) && !empty($data['localheadimgurl']) ? $data['localheadimgurl'] : $data['headimgurl'];
        $datap['localheadimgurl'] = isset($data['localheadimgurl']) && !empty($data['localheadimgurl']) ? $data['localheadimgurl'] : $data['headimgurl'];
        if (isset($data['cat_id'])) {
            $datap['cat_id'] = $data['cat_id'];
        }
        if (isset($data['user_type'])) {
            $datap['user_type'] = $data['user_type'];
        }
        if (isset($data['recommend'])) {
            $datap['recommend'] = $data['recommend'];
        }

        if (isset($data['user_type2'])) {
            $datap['user_type2'] = $data['user_type2'];
        }
        if (isset($data['nickname'])) {
            $user_id = usersMysql::name('letter_users')->where(array('nickname' => $data['nickname']))->value('user_id');
            if ($user_id > 0) {
                exception("此昵称已被使用过了！", 110030);
            }
        }
        $userd = usersMysql::name('letter_users')->insertGetId($datap);
        if ($userd) { //
            return $userd;
        } else {
            exception('注册失败！', 10000003);
        }
    }

    /**
     * 扣除余额并记录日志
     * user_id
     * money
     * money_type
     * order_id
     * admin_id
     * memo
     */
    public static function updateMoney($post) {
        usersMysql::startTrans();
        $r = usersMysql::updateMoney($post['user_id'], $post['money']);
        if ($r == false) {
            usersMysql::rollback();
            return false;
        }

        //money_type 24 获得佣金
        if ($post['money_type'] == 24) {
            $r1 = usersMysql::updateWithdrawMoney($post['user_id'], $post['money']);
            if ($r1 == false) {
                usersMysql::rollback();
                return false;
            }
        }
        //money_type 28邀请获得,29充值分润 
        if (in_array($post['money_type'], array(28, 29))) {
            $redis = new userRedis();
            $key = "invite:" . $post['user_id'];
            $redis->incr($key);
            $key = "invitetotal:" . $post['user_id'];
            $redis->incr($key);
        }

        //记录日志
        $post['add_time'] = time();
        $r2 = usersMysql::name('user_money_log')->insertGetId($post);
        if ($r2 > 0) {
            usersMysql::commit();
            return true;
        }
        usersMysql::rollback();
        return false;
    }

    /**
     * 更新会员的输赢情况
     * user_id
     * wins
     * lose
     */
    public static function updateWinLos($post) {
        $r1 = true;
        $r = true;
        if (isset($post['wins'])) {
            if ($post['wins'] == 1) {
                $r = usersMysql::name('letter_users')->where(array('user_id' => $post['user_id']))->setInc('wins', 1);
            } elseif ($post['wins'] == -1) {
                $r = usersMysql::name('letter_users')->where(array('user_id' => $post['user_id']))->setDec('wins', 1);
            }
        }
        if (isset($post['lose'])) {
            if ($post['lose'] == 1) {
                $r1 = usersMysql::name('letter_users')->where(array('user_id' => $post['user_id']))->setInc('lose', 1);
            } elseif ($post['lose'] == -1) {
                $r1 = usersMysql::name('letter_users')->where(array('user_id' => $post['user_id']))->setDec('lose', 1);
            }
        }
        return $r1;
    }

    /**
     * 个人中心
     */
    public static function usercenter($user_id = '') {
        //用户信息
        $data['nickname'] = '';
        $data['headimgurl'] = '';
        $data['lv_name'] = '';
        $data['lv'] = 0;
        $data['point'] = 0;
        $data['money'] = 0;
        $data['order_count'] = 0;
        $data['collect_count'] = 0;
        $data['comment_count'] = 0;
        $data['friends_count'] = 0;
        $data['close_ios'] = 0;
        $data['rank'] = 0;
        $data['user_type'] = 0;
        $data['unionid'] = "";
        $data['mobile'] = "";
        $data['invitetotal'] = 0;
        $zhupancount = 0;
        if ($user_id) {
            $data = self::userInfo($user_id, 'user_id,nickname,headimgurl,lv,point,money,order_count,collect_count,comment_count,friends_count,localheadimgurl,user_type,unionid,mobile');
            $redis = new userRedis();
            $key = "invitetotal:" . $user_id;
            $newtotal = $redis->get($key);
            $data['invitetotal'] = empty($newtotal) ? 0 : $newtotal;
            if ($data) {
                $data['lv_name'] = pointBn::getLevel($data['lv'])['name'];
                $data['rank'] = pointBn::getLevel($data['lv'])['rank'];
            }
            $zp['user_id'] = $user_id;
            $zp['type_id'] = 2;
            $zpcount = hdBn::isfirsttime($zp);
            $zhupancount = $zpcount['free_time'] - $zpcount['logcount'] > 0 ? $zpcount['free_time'] - $zpcount['logcount'] : 0;
        }

        $data['myinite_txt'] = '你和自由只差一个好友！';
        $data['myshare_text'] = '邀新人，享分润，奖壕礼！';
        $data['jindou_txt'] = '火热迎新年！充值就送！';
        // 兑吧 1开 0关
        $data['duiba'] = 1;
        $data['zhupancount'] = $zhupancount;
        return $data;
    }

    /**
     * 用户登录
     */
    public static function login($post) {
        //获取加密后的手机号
        $encodmobile = $post['mobile'];
        $flag = usersMysql::name('letter_users')
                ->field('user_id')
                ->where(array("mobile" => $encodmobile))
                ->find();
        if (isset($flag)) {
            $data['user_lasttime'] = time();
            //  $data['user_first'] = $flag['user_first'] == 0 ? $flag['user_first'] + 1 : $flag['user_first']; 

            /* 重现保存密码与上一次的登陆时间 */
            $result = usersMysql::name('letter_users')->where(array("user_id" => $flag['user_id']))->update($data);

            if ($result) {
                $flag = User::userInfo($flag['user_id']);
            } else {
                exception('免注册登录失败', 110035);
            }
        } else {
            exception('免注册登录失败', 110036);
        }
        //积分操作
//        $postp['user_id'] = $flag['user_id'];
//        $postp['change_type'] = 1;
//        $postp['source_type'] = 7;
//        pointModel::updatePoint($postp);
        //生成sso     
        $userid = $flag['user_id'];
        $sso = User::calcSso($userid);
        //unset($flag['user_id']); 
        $flag['sso'] = $sso;
        //是否已签到 
        return $flag;
    }

    /*
     *
     * 注册第一步判断手机号以及验证码控制器
     *
     */

    public static function register($data) {
        //获取加密后的手机号
        $encodmobile = $data['mobile'];
        $istest = true;

        if (in_array($encodmobile, array(13800000001))) {
            $istest = false;
        }
        $code_type = isset($data['code_type']) ? $data['code_type'] : 1;
        if (!self::verfiytest($data, $code_type) && $istest) {
            exception('验证码错误', 110021);
        }
        $userid = usersMysql::get(['mobile' => $encodmobile]);
        if (!empty($userid) || $istest == false) {
            return self::login($data);
        }

        $datap['mobile'] = $encodmobile;
        $datap['add_time'] = $datap['user_lasttime'] = $datap['user_updatetime'] = time();
        $userinfo = new usersMysql();
        usersMysql::startTrans();
        try {
            $userd = $userinfo->insertGetId($datap);
            //激请码
            $rinvite = true;
            $invite = array();
            if (isset($data['invite_code']) && !empty($data['invite_code'])) {
                $invite['invite_code'] = $data['invite_code'];
                $invite['user_id'] = $userd;
                $invite['add_time'] = time();
                $rinvite = usersMysql::name('user_invite')->insert($invite);
            }

            if ($userd && $rinvite == true) {
                //赠品金豆
                /* $updatemoney['user_id'] = $userd;
                  $updatemoney['money_type'] = 27;
                  $updatemoney['money'] = 55;
                  $updatemoney['memo'] = "注册获得";
                  $r2 = self::updateMoney($updatemoney);

                  if ($r2 != true) {
                  usersMysql::rollback();
                  exception('注册失败', 110038);
                  } */
                //赠品嗨豆
                $pointdata = pointBn::updatePointBySource(array('user_id' => $userd, 'source_type' => 10));
                //赠送券
                $coupon['coupon_endtime'] = date("Y-m-d", strtotime("+7 day"));
                $coupon['coupon_id'] = 9;
                $coupon['user_id'] = $userd;
                $coupontotal = 2;
                $r3 = couponBn::send($coupon);
                if ($r3 != true) {
                    usersMysql::rollback();
                    exception('注册失败', 110038);
                }
                //赠送券
                $coupon['coupon_endtime'] = date("Y-m-d", strtotime("+30 day"));
                $coupon['coupon_id'] = 10;
                $coupon['user_id'] = $userd;
                $r4 = couponBn::send($coupon);
                if ($r4 != true) {
                    usersMysql::rollback();
                    exception('注册失败', 110038);
                }
                //赠送券
                if (isset($data['channel_source']) && $data['channel_source'] == 'oppo') {
                    $coupontotal = 3;
                    $coupon['coupon_endtime'] = date("Y-m-d", strtotime("+30 day"));
                    $coupon['coupon_id'] = 11;
                    $coupon['user_id'] = $userd;
                    $r4 = couponBn::send($coupon);
                    if ($r4 != true) {
                        usersMysql::rollback();
                        exception('注册失败', 110038);
                    }
                }
                $user = self::userInfo($userd);
                $user['sso'] = User::calcSso($user['user_id']);
                $user['total_point'] = $pointdata['total_point'];
                $user['point'] = $pointdata['point'];
                $user['sign_money'] = 0;
                $user['coupon_total'] = $coupontotal;
                $user['is_register'] = 1;
                $user['coupon_name'] = "7折";
                //邀请码注册邀请人赠送 
                if ($invite) {
                    //赠品金豆
                    $updatemoney['user_id'] = $invite['invite_code'];
                    $updatemoney['money_type'] = 28;
                    $updatemoney['money'] = 10;
                    $invitemobile = substr_replace($data['mobile'], '***', 3, 6);
                    $updatemoney['memo'] = "邀请" . $invitemobile . "注册获得";
                    $r2 = self::updateMoney($updatemoney);

                    if ($r2 != true) {
                        usersMysql::rollback();
                        exception('注册失败', 110038);
                    }
                    //赠品嗨豆
                    $pointdata = pointBn::updatePointBySource(array('user_id' => $invite['invite_code'], 'source_type' => 12, 'source_id' => $userd));
                    //赠送券
                    $coupon['coupon_endtime'] = date("Y-m-d", strtotime("+7 day"));
                    $coupon['coupon_id'] = 8;
                    $coupon['user_id'] = $invite['invite_code'];
                    $coupon['coupon_memo'] = "邀请" . $invitemobile . "注册获得";
                    $r3 = couponBn::send($coupon);
                    if ($r3 != true) {
                        usersMysql::rollback();
                        exception('注册失败', 110038);
                    }
                    //进入消息
                    //添加系统消息
                    $dataadd['msg_type'] = 4;
                    $dataadd['user_id'] = $invite['invite_code'];
                    $dataadd['content'] = '恭喜您邀请了小伙伴' . $invitemobile . '，奖励已到账，小伙伴后续充值您还有分润哦~';
                    $dataadd['title'] = '新人邀请';
                    $dataadd['type'] = 4;
                    $dataadd['msg_source_id'] = $userd;
                    userMessageBn::add($dataadd);
                    //推送 
                    $datapush['name'] = 21;
                    $datapush['redirect'] = "";
                    $datapush['other'] = $invite['invite_code'];
                    $datapush['content'] = "奖励已到账！恭喜您，成功邀请小伙伴！";
                    $datapush['title'] = "新人邀请";
                    $datapush['send_time'] = time();
                    $datapush['receive_group'] = json_encode(array(2041));
                    pushBn::add($datapush);
                }

                usersMysql::commit();
                unset($user['user_id']);
                return $user;
            } else {
                exception('免注册登录失败！', 110025);
            }
        } catch (\Exception $e) {
            usersMysql::rollback();
            exception($e->getMessage(), $e->getCode());
        }
    }

    /*
     * 验证验证码
     * @$flag  0 密码验证码 1 注册验证码
     * */

    public static function verfiytest($data, $flag) {
        $code = $data['user_code'];
        $retuen = false;
        $redis = new userRedis();
        if (substr($redis->get("code:" . $data['mobile'] . $flag), 0, 12) == $data['mobile'] . $flag) {
            $retuen = $redis->get('helloweba_num:' . $data['mobile'] . $flag) == $code ? true : false;
        }
        if ($retuen) {
            $redis->del("code:" . $data['mobile'] . $flag);
            $redis->del('helloweba_num:' . $data['mobile'] . $flag);
        }
        return ($retuen);
    }

    /**
     *
     * 验证码控制器
     * mobile
     * register 1 => "注册", 2 => "绑定",3 => "忘记密码"
     * type weixin,qq,sina
     *
     */
    public static function codebutton($post) {
        $mobile = $post['mobile'];
        $register = $post['code_type'];
        //获取加密后的手机号
        $encodmobile = $mobile;
        $redis = new userRedis();
        /* 同个手机号码发送超过一分钟才可以重新发送！ */
        $sessipontime = substr($redis->get("code:" . $mobile . $register), 12);
        if (substr($redis->get("code:" . $mobile . $register), 0, 12) == $mobile . $register) {
            if (time() - $sessipontime <= 60)
                exception('60秒内只能发送一次短信', 110018);
        }
//        /* 搜索是否存在手机号 注册和找会密码 */
        if ($register == 4) {
            self::forgetregige($encodmobile, $register);
        } elseif ($register == 2) { //用户判断
            $user_id = $post['user_id'];
            quickloginBn::mobilecode($encodmobile, $user_id);
        }
        $params['code'] = User::code($mobile, $register);
        $params['mobile'] = $mobile;
        $params['register'] = $register;
        $MessageBn = new MessageBn($params);
        $result = $MessageBn->pushmessage($params);
        return $result;
    }

    /*
     *
     * 注册忘记密码验证码
     * */

    public static function forgetregige($mobile, $register) {
        $flag = usersMysql::name('letter_users')
                ->field('user_id')
                ->where(array("mobile" => $mobile))
                ->find();
        if ($register == 1) {
            /* 判断是否注册，如果注册则不让发送验证码 */
            if (!empty($flag))
                exception('此手机已注册', 110026);
        }else if ($register == 3) {
            if (empty($flag))
                exception('此手机未注册', 110028);
        }else if ($register == 4) {
            if (!empty($flag))
                exception('此手机已注册', 110026);
        }
        return true;
    }

    /*
     *
     * 生成验证码
     * 手机号码作为session 的标识
     *
     * */

    public static function code($mobile, $register) {
        $code = rand(1000, 9999);

        //4位验证码也可以用rand(1000,9999)直接生成
        //将生成的验证码写入session，备验证时用
        $redis = new userRedis();
        $redis->set('helloweba_num:' . $mobile . $register, $code, 65);
        $redis->set("code:" . $mobile . $register, $mobile . $register . time(), 65);
        return $code;
    }

    /*
     *
     * 我的战绩
     *
     * */

    public static function myrecordlist($post) {
        $field = 'user_id,nickname,headimgurl,user_type,point,money,wins,lose,user_sign,localheadimgurl,sex,status,lv,scheme_count,wins,drow,lose';
        $userinfo = self::userInfo($post['user_id'], $field);
        return $userinfo;
    }

    /*
     *
     * 编辑
     *
     */

    public static function userdetail($post) {
        if (isset($post['nickname'])) {
            $user_id = usersMysql::name('letter_users')->where(array('nickname' => $post['nickname']))->value('user_id');
            if ($user_id > 0) {
                if ($user_id != $post['user_id']) {
                    exception("此昵称已被使用过了！", 110030);
                }
            }
        }
        /* 头像 */
        $userimg = isset($post['headimgurl']) ? $post['headimgurl'] : "";
        if ($userimg) {
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $userimg)) {
                $post['headimgurl'] = imageModel::uploadav($userimg)['dest_file_name'];
            } else {

                if (strpos($userimg, 'http://') !== false) {
                    $post['headimgurl'] = $userimg;
                } else {
                    $resourceHost = Configbn::get('upyun.resourcesHost');
                    $post['headimgurl'] = $resourceHost . $userimg;
                }
            }
        }
        $post['user_updatetime'] = time();
        $post['sex'] = isset($post['sex']) ? $post['sex'] : 1;
        $flag = usersMysql::name('letter_users')->update($post);
        if ($flag) {

            $userinfo = self::userInfo($post['user_id']);
            $userinfo['sso'] = User::calcSso($userinfo['user_id']);
            return $userinfo;
        } else
            exception('修改失败', 104);
    }

    /*
     * 查询短信列表`2wrdac
     *
     * */

    public static function messageinfo($params) {
        self::_checkPageAndCount($params);
        $where = self::_getWhere($params);
        $pageParam['query'] = self::_getQuery($params);
        $list = usersMysql::name('user_code')
                ->where($where)
                ->order('id desc')
                ->paginate($params['count'], false, $pageParam);
        $code_type = self::code_type();
        foreach ($list as $k => $val) {
            $list[$k]['code_type'] = isset($code_type[$val['code_type']]) ? $code_type[$val['code_type']] : '';
        }
        return $list;
    }

    /**
     * 获取用户列表 

     */
    public static function getuserlist($params, $field = '') {
        if ($field == '') {
            $field = "user_id";
        }
        $where = self::_getWhere($params);
        $listdata = usersMysql::name('letter_users')
                ->field($field)
                ->where($where)
                ->select();

        return $listdata;
    }

    /**
     * 获取用户列表

     */
    public static function admingetuserlist($params, $field = '') {

        $where = self::_getWhere($params);
        $listdata = usersMysql::name('letter_users')
                ->field($field)
                ->where('user_type in(20,30)')
                ->where($where)
                ->select();
        foreach ($listdata as $key => $val) {
            $listdata[$key]['user_type'] = $val['user_type'] == 20 ? '民间高手' : '专家';
            $listdata[$key]['cat_id'] = $val['cat_id'] == 1 ? '足球' : '篮球';
        }
        return $listdata;
    }

    /**
     * 专家列表足球篮球
     * @param array $params
     * cat_id
     * user_id 当前用户
     * page
     * count
     *
     */
    public static function recommendlist($params) {
        self::_checkPageAndCount($params);
        $where = array("user_type" => 30);
        $starttime = time() - 7 * 3600 * 24;
        $endtime = time();
        $listdata = usersMysql::name('letter_users')
                ->field("u.user_id,nickname,headimgurl,localheadimgurl,u.wins,u.lose,user_sign,lv,round(round(u.win20/(u.win20+u.lose20),2)*100) as winrate")
                ->alias('u')
                ->where($where)
                ->order("u.win20 desc")
                ->limit(0, $params['count'])
                ->select();
        if (!empty($listdata)) {
            $listdata = self::_adapterexpertList($listdata, $params);
        }
        if (isset($params["need_total"]) && $params["need_total"] == 1) {
            $count = 10;
            return array("listdata" => $listdata, "total" => $count);
        }
        return array("listdata" => (array) $listdata);
    }

    /**
     * 当前用户金额
     */
    public static function currentMoney($user_id) {
        return userMysql::name('letter_users')
                        ->where(array('user_id' => $user_id))
                        ->value('money');
    }

    /**
     * 检验金额
     * $post['money']
     * $post['user_id']
     */
    public static function checkMoney($post) {
        return usersMysql::name('letter_users')
                        ->where(array('user_id' => $post['user_id'], 'money' => array('>=', $post['money'])))
                        ->count();
    }

    /**
     * 用户合并
     * from_user_id
     * to_user_id
     */
    public static function userMerge($post) {
        $fromdata = usersMysql::name('letter_users')->find($post['from_user_id']);
        $todata = usersMysql::name('letter_users')->find($post['to_user_id']);
        usersMysql::startTrans();
        try {
            //嗨豆 记录 
            $r1 = usersMysql::name('user_point_log')->where(array('user_id' => $post['from_user_id']))->update(array('user_id' => $post['to_user_id']));

            //金豆 记录，
            $r2 = usersMysql::name('user_money_log')->where(array('user_id' => $post['from_user_id']))->update(array('user_id' => $post['to_user_id']));

            //竞彩 记录
            $r3 = usersMysql::name('scheme_jc')->where(array('user_id' => $post['from_user_id']))->update(array('user_id' => $post['to_user_id']));

            //方案记录
            $r4 = usersMysql::name('scheme')->where(array('user_id' => $post['from_user_id']))->update(array('user_id' => $post['to_user_id']));
            //消息记录
            $r5 = usersMysql::name('user_message')->where(array('user_id' => $post['from_user_id']))->update(array('user_id' => $post['to_user_id']));

            //红包
            $r6 = usersMysql::name('user_red')->where(array('user_id' => $post['from_user_id']))->update(array('user_id' => $post['to_user_id']));
            $r7 = usersMysql::name('user_red_log')->where(array('user_id' => $post['from_user_id']))->update(array('user_id' => $post['to_user_id']));
            //签到
            $r8 = usersMysql::name('user_sign')->where(array('user_id' => $post['from_user_id']))->update(array('user_id' => $post['to_user_id']));
            //充值 
            $r9 = usersMysql::name('user_cz')->where(array('user_id' => $post['from_user_id']))->update(array('user_id' => $post['to_user_id']));
            //优惠券

            $r11 = usersMysql::name('user_coupon_log')->where(array('user_id' => $post['from_user_id']))->update(array('user_id' => $post['to_user_id']));
            //评论
            $r12 = usersMysql::name('user_comment')->where(array('user_id' => $post['from_user_id']))->update(array('user_id' => $post['to_user_id']));
            //订单
            $r13 = usersMysql::name('orders')->where(array('user_id' => $post['from_user_id']))->update(array('user_id' => $post['to_user_id']));

            //嗨豆，金豆，等级，状态
            $userupdata['point'] = $todata['point'] + $fromdata['point'];
            $userupdata['money'] = $todata['money'] + $fromdata['money'];
            $userupdata['wins'] = $todata['wins'] + $fromdata['wins'];
            $userupdata['drow'] = $todata['drow'] + $fromdata['drow'];
            $userupdata['lose'] = $todata['lose'] + $fromdata['lose'];
            $userupdata['lv'] = $todata['lv'] > $fromdata['lv'] ? $todata['lv'] : $fromdata['lv'];
            $userupdata['headimgurl'] = $todata['headimgurl'] ? $todata['headimgurl'] : $fromdata['headimgurl'];
            $userupdata['nickname'] = $todata['nickname'] ? $todata['nickname'] : $fromdata['nickname'];
            $userupdata['mobile'] = $todata['mobile'] ? $todata['mobile'] : $fromdata['mobile'];
            $userupdata['user_sign'] = $todata['user_sign'] ? $todata['user_sign'] : $fromdata['user_sign'];
            $userupdata['unionid'] = $todata['unionid'] ? $todata['unionid'] : $fromdata['unionid'];
            $userupdata['openid'] = $todata['openid'] ? $todata['openid'] : $fromdata['openid'];
            $userupdata['uuid'] = $todata['uuid'] ? $todata['uuid'] : $fromdata['uuid'];

            $r1 = usersMysql::name('letter_users')->where(array('user_id' => $post['to_user_id']))->update($userupdata);
            $r2 = usersMysql::name('letter_users')->where(array('user_id' => $post['from_user_id']))->update(array('status' => 30, 'nickname' => '', 'openid' => '', 'unionid' => '', 'uuid' => ''));
            $insertdata = array('from_user_id' => $post['from_user_id'], 'to_user_id' => $post['to_user_id'], 'add_time' => time(), 'memo' => json_encode($fromdata));
            usersMysql::name('user_merge')->insert($insertdata);
            usersMysql::commit();
            return true;
        } catch (\Exception $e) {
            usersMysql::rollback();
            exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 更新用户信息
     */
    public static function updateUserinfo($user_id, $updata) {
        $r1 = usersMysql::name('letter_users')->where(array('user_id' => $user_id))->update($updata);
        return $r1;
    }

    /**
     * 后台会员列表
     * page
     * count
     * need_total
     */
    public static function majialist($params) {
        self::_checkPageAndCount($params);
        $where = self::_getWhere($params);
        $listdata = usersMysql::name('letter_users')
                ->field('user_id,nickname')
                ->alias('u')
                ->where($where)
                ->select();
        if ($listdata) {
            foreach ($listdata as $k => $v) {
                $listdata[$k]['sso'] = self::calcSso($v['user_id']);
            }
        }

        return array("listdata" => (array) $listdata);
    }

    /*
     *
     * 编辑
     *
     */

    public static function updateheadimgurl2($post) {
        $userimg = isset($post['imgurl']) ? $post['imgurl'] : "";
        if ($userimg) {

            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $userimg)) {

                $data['imgurl'] = uploadBn::uploadav($userimg)['dest_file_name'];

                return $data['imgurl'];
            }
        }
        exception("上传失败！", 110030);
    }

    /**
     * 登录时长
     * str_time
     * end_time
     * 
     */
    public static function memberpath($post) {
        $hourdata = usersMysql::name('user_access')->field('(MAX(add_time)-MIN(add_time))/3600 as hour,user_id')
                ->where(array('add_time' => array('between', [$post['str_time'], $post['end_time']])))
                ->group('user_id')
                ->select();
        foreach ($hourdata as $k => $v) {
            usersMysql::name('letter_users')->where(array("user_id" => $v['user_id']))->setInc('logintime', $v['hour']);
        }
        return true;
    }

    /**
     * 登录统计
     */
    public static function userlogincount($user_id) {
        $redis = new userRedis();
        $userlogin = $redis->get("login:" . $user_id);
        $time = strtotime(date("Y-m-d 23:59:59")) - time();
        if ($userlogin) {
            //  $redis->set("login:" . $user_id, $user_id, $time);
            return true;
        }
      
        usersMysql::name('letter_users')->where(array("user_id" => $user_id))->setInc('logincount', 1);
        usersMysql::name('letter_users')->where(array("user_id" => $user_id))->update(array('user_lasttime' => time()));
        $time = strtotime(date("Y-m-d 23:59:59")) - time();
        $redis->set("login:" . $user_id, $user_id, $time);
        return true;
    }

    /**
     * 用户留存
     */
    public static function userkeeplist($params) {
        self::_checkPageAndCount($params);
        $where = self::_getWhere($params);
        $query = self::_getQuery($params);
        $pageParam['query'] = $query;
        $listdata = userMysql::name('user_keeplog')
                ->where($where)
                ->limit($params['offset'], $params['count'])
                ->order('add_time desc')
                ->paginate($params['count'], false, $pageParam);
        if (!empty($listdata)) {
            // $listdata = self::_userkeeplist($listdata);
        }
        return $listdata;
    }

    /**
     * 当天的留存情况
     */
    public static function curentuserkeep() {
        $listdata = userMysql::name('user_keeplog')
                ->where($where)
                ->limit($params['offset'], $params['count'])
                ->order('add_time desc')
                ->paginate($params['count'], false, $pageParam);
    }

}
